package top.truehaku.generator.code.domain.model.column;

import lombok.Getter;
import lombok.Setter;
import top.truehaku.generator.common.domain.ValueObject;
import top.truehaku.generator.common.util.StringUtils;

import java.util.Arrays;
import java.util.List;

public class ColumnComment implements ValueObject<ColumnComment> {

    @Getter@Setter
    private String columnComment;

    public ColumnComment(String columnComment) {
        if (StringUtils.isBlank(columnComment)){
            throw new IllegalArgumentException("字段注释必填");
        }
        this.columnComment = columnComment;
    }

    @Override
    public boolean sameValueAs(ColumnComment other) {
        return other!=null&&this.columnComment.equals(other.columnComment);
    }

    private String[] splitComment(){
        return this.columnComment.split("\\|");
    }

    private String indexOf(int index){
        String[] parts = this.splitComment();
        return parts.length>index?parts[index]:null;
    }

    /**
     * 获取注释
     * @return
     */
    public String getComment(){
        String comment = indexOf(0);
        return StringUtils.subBefore(comment,'(',false);
    }

    /**
     * 获取查询条件
     * @return
     */
    public String getCondition(){
        String condition = indexOf(1);
        return StringUtils.isBlank(condition)||condition.startsWith("cb")?null:StringUtils.subBefore(condition,'(',false);
    }

    /**
     * 是否为查询条件
     * @return
     */
    public Boolean isCondition(){
        return StringUtils.isNotBlank(getCondition());
    }

    /**
     * 是否为组合字段
     * @return
     */
    public Boolean isCombine(){
        String condition = indexOf(2);
        return StringUtils.isNotBlank(condition);
    }

    /**
     * 获取补充说明
     * @return
     */
    public String getRemark(){
        String comment = indexOf(0);
        assert comment != null;
        int index = comment.lastIndexOf('(');
        return index>-1?comment.substring(index + 1, comment.length()-1):null;
    }

    /**
     * 获取组合字段
     * @return
     */
    public List<String> getCombineColumns(){
        String columns = indexOf(2);
        return StringUtils.isNotBlank(columns)&&isCombine()?Arrays.asList(columns.split(",")):null;
    }


    public static void main(String[] args) {
        String str = "客户来源|eq";
        ColumnComment columnComment = new ColumnComment(str);
        System.out.println(columnComment.getComment());
        System.out.println(columnComment.getRemark());
        System.out.println(columnComment.getCondition());
        System.out.println(columnComment.getCombineColumns());
    }
}
